package com.ict.web.utils.pdf;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ict.common.utils.StringUtils;
import com.ict.web.constant.Constants;
import com.ict.web.domain.LastCheck;
import com.ict.web.domain.ProjectManagement;
import com.ict.web.mapper.LastCheckMapper;
import com.ict.web.service.IProjectManagementService;
import com.ict.web.vo.PerIndectorsDetailsVo;
import com.ict.web.vo.PerformanceStatisticsListVo;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

@Component
public class PdfUtil {
    @Autowired
    private  LastCheckMapper lastCheckMapper;
    @Autowired
    private  IProjectManagementService projectManagementService;
    // 基础配置
    public static BaseFont bfChinese;


    public static PdfUtil pdfUtil;

    @PostConstruct
    public void init() {
        pdfUtil = this;
        pdfUtil.lastCheckMapper = this.lastCheckMapper;
        pdfUtil.projectManagementService = this.projectManagementService;
    }


    static {
        try {
//            bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
//            bfChinese = BaseFont.createFont("C:/Users/xc/Desktop/simsun.ttc,0",BaseFont.IDENTITY_H,BaseFont.NOT_EMBEDDED);
            bfChinese = BaseFont.createFont("/data01/project/yuzhongqu/service/manage/SIMSUN.TTC,0",BaseFont.IDENTITY_H,BaseFont.NOT_EMBEDDED);

        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 基础样式
    public static Font TITLE_FONT = new Font(bfChinese, 20, Font.BOLD);
    public static Font NODE_FONT = new Font(bfChinese, 15, Font.BOLD);
    public static Font BLOCK_FONT = new Font(bfChinese, 13, Font.BOLD, BaseColor.BLACK);
    public static Font INFO_FONT = new Font(bfChinese, 12, Font.NORMAL, BaseColor.BLACK);
    public static Font CONTENT_FONT = new Font(bfChinese, 12, Font.NORMAL);

    public static DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");


    private PdfUtil() {
    }

    /**
     * 段落样式获取
     */
    public static Paragraph getParagraph(String content, Font font, Integer alignment) {
        Paragraph paragraph = new Paragraph(content, font);
        if (alignment != null && alignment >= 0) {
            paragraph.setAlignment(alignment);
        }
        return paragraph;
    }

    /**
     * 表格生成
     */
    public static PdfPTable getPdfPTable01(int numColumns, float totalWidth) throws Exception {
        // 表格处理
        PdfPTable table = new PdfPTable(numColumns);
        // 设置表格宽度比例为%100
        table.setWidthPercentage(100);
        // 设置宽度:宽度平均
        table.setTotalWidth(totalWidth);
        // 锁住宽度
        table.setLockedWidth(true);
        // 设置表格上面空白宽度
        table.setSpacingBefore(10f);
        // 设置表格下面空白宽度
        table.setSpacingAfter(10f);

        table.setPaddingTop(50);
        table.setSplitLate(false);
        return table;
    }

    /**
     * 表格内容
     */
    public static PdfPCell getPdfPCell(Phrase phrase) {
        return new PdfPCell(phrase);
    }

    /**
     * 表格内容带样式
     */
    public static void addTableCell(PdfPTable dataTable, Font font, List<String> cellList) {
        for (String content : cellList) {
            dataTable.addCell(getParagraph(content, font, -1));
        }
    }

    public static PdfPTable setPdfTable(List<PerformanceStatisticsListVo> list) throws Exception {
        PdfPTable dataTable = getPdfPTable01(7, 500);
        // 设置表格
        List<String> tableHeadList = tableHead();
        List<List<String>> tableDataList = getTableData(list);
        PdfUtil.addTableCell(dataTable, CONTENT_FONT, tableHeadList);
        for (List<String> tableData : tableDataList) {
            PdfUtil.addTableCell(dataTable, CONTENT_FONT, tableData);
        }
        return dataTable;
    }

    private static List<List<String>> getTableData(List<PerformanceStatisticsListVo> list) {
        List<List<String>> tableDataList = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            List<String> tableData = new ArrayList<>();
            tableData.add(list.get(i).getName());
            tableData.add(list.get(i).getCompany());
            tableData.add(list.get(i).getNature().equals("0") ? "年度项目" : "增补项目");
            switch (list.get(i).getType()){
                case "0":tableData.add("建设类(新开工)");break;
                case "1":tableData.add("建设类(续建)");break;
                case "2":tableData.add("购买服务类");break;
                case "3":tableData.add("运维类");break;
                case "4":tableData.add("其他");break;
            };
            tableData.add(list.get(i).getAnnualProjectPlanName());
            if (StringUtils.isNotNull(list.get(i).getEndTime())) {
                String time = getEndTime(list.get(i).getProjectId());
                tableData.add(time);
            } else {
                tableData.add(null);
            }
            tableData.add(String.valueOf(list.get(i).getPerformanceScore()));
            tableDataList.add(tableData);
        }
        return tableDataList;
    }

    private static List<String> tableHead() {
        List<String> tableHeadList = new ArrayList<>();
        tableHeadList.add("项目名称");
        tableHeadList.add("项目单位");
        tableHeadList.add("项目性质");
        tableHeadList.add("项目类别");
        tableHeadList.add("计划名称");
        tableHeadList.add("考核结束时间");
        tableHeadList.add("绩效分数");
        return tableHeadList;
    }

    public static PdfPTable setDetailTable(List<PerIndectorsDetailsVo> list) throws Exception {
        PdfPTable dataTable = getPdfPTable01(4, 500);
        // 设置表格
        List<String> tableHeadList = tableDetailHead();
        List<List<String>> tableDataList = getTableDetailData(list);
        PdfUtil.addTableCell(dataTable, CONTENT_FONT, tableHeadList);
        for (List<String> tableData : tableDataList) {
            PdfUtil.addTableCell(dataTable, CONTENT_FONT, tableData);
        }
        return dataTable;
    }


    private static List<String> tableDetailHead() {
        List<String> tableHeadList = new ArrayList<>();
        tableHeadList.add("指标名称");
        tableHeadList.add("指标数值");
        tableHeadList.add("指标得分");
        tableHeadList.add("指标权重");
        return tableHeadList;
    }

    private static List<List<String>> getTableDetailData(List<PerIndectorsDetailsVo> list) {
        List<List<String>> tableDataList = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            List<String> tableData = new ArrayList<>();
            tableData.add(list.get(i).getIndicatorsName());
            String regulation = new String();
            String value = String.valueOf(list.get(i).getValue());
            switch (list.get(i).getRegulation()) {
                case "0":
                    regulation = ">" + value;
                    break;
                case "1":
                    regulation = "≥" + value;
                    break;
                case "2":
                    regulation = "=" + value;
                    break;
                case "3":
                    regulation = "≤" + value;
                    break;
                case "4":
                    regulation = "<" + value;
                    break;
            }
            tableData.add(regulation);
            tableData.add(String.valueOf(list.get(i).getScore()));
            tableData.add(list.get(i).getIndicatorsWeight().toString());
            tableDataList.add(tableData);
        }
        return tableDataList;
    }

    public static Document createInformation(Document document, PerformanceStatisticsListVo performanceStatisticsListVo) throws Exception {
        String nameS = performanceStatisticsListVo.getName();
        if (!StringUtils.isNotEmpty(nameS)) {
            nameS = new String();
        }
        Paragraph nameP = new Paragraph("", PdfUtil.INFO_FONT);
        Chunk name = new Chunk("项目名称：" + nameS + "\n");
        nameP.add(name);
        nameP.setSpacingBefore(20);
        document.add(nameP);

        Paragraph natureP = new Paragraph("", PdfUtil.INFO_FONT);
        Chunk nature = new Chunk("项目性质：" + (performanceStatisticsListVo.getNature().equals("0") ? "年度项目" : "增补项目") + "\n");
        natureP.add(nature);
        natureP.setSpacingBefore(20);
        document.add(natureP);

        String annualProjectPlanName = performanceStatisticsListVo.getAnnualProjectPlanName();
        if (!StringUtils.isNotEmpty(annualProjectPlanName)) {
            annualProjectPlanName = new String();
        }
        Paragraph planP = new Paragraph("", PdfUtil.INFO_FONT);
        Chunk plan = new Chunk("所属计划：" + annualProjectPlanName + "\n");
        planP.add(plan);
        planP.setSpacingBefore(20);
        document.add(planP);

        String companyS = performanceStatisticsListVo.getCompany();
        if (!StringUtils.isNotEmpty(companyS)) {
            companyS = new String();
        }
        Paragraph companyP = new Paragraph("", PdfUtil.INFO_FONT);
        Chunk company = new Chunk("项目单位：" + companyS + "\n");
        companyP.add(company);
        companyP.setSpacingBefore(20);
        document.add(companyP);

        Paragraph typeP = new Paragraph("", PdfUtil.INFO_FONT);
        Chunk type = new Chunk("项目类别：" + reType(performanceStatisticsListVo.getType()) + "\n");
        typeP.add(type);
        typeP.setSpacingBefore(20);
        document.add(typeP);


        String string = getTime(performanceStatisticsListVo.getProjectId());
        Paragraph timeP = new Paragraph("", PdfUtil.INFO_FONT);
        Chunk time = new Chunk("考核时间：" + string + "\n");
        timeP.add(time);
        timeP.setSpacingBefore(20);
        document.add(timeP);

        return document;
    }
    public static String reType(String type){
        String s = null;
        switch (type){
            case "0":s= "建设类(新开工)";break;
            case "1":s= "建设类(续建)";break;
            case "2":s= "购买服务类";break;
            case "3":s= "运维类";break;
            case "4":s= "其他";break;
        };
        return s;
    }

    /**
     * 考核结束数据
     * @param proId
     * @return
     */
    public static String getEndTime(Long proId){
        ProjectManagement projectManagement = pdfUtil.projectManagementService.getById(proId);
        LambdaQueryWrapper<LastCheck> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(LastCheck::getLastCheckId,projectManagement.getLastCheckId())
                .eq(LastCheck::getIsDelete, Constants.DELETE_STATUS_NORMAL);
        LastCheck lastCheck = pdfUtil.lastCheckMapper.selectOne(lambdaQueryWrapper);
        //考核开始时间为终验时间
        LocalDateTime localDateTime = lastCheck.getLastAdoptTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
        //考核时间暂定为大于终验时间半年
        LocalDateTime localDateTimeEndTime = localDateTime.plusMonths(6);
        String endTime = String.valueOf(localDateTimeEndTime).substring(0,String.valueOf(localDateTimeEndTime).lastIndexOf("T"));
        return endTime;
    }
    /**
     * 返回考核时间段
     * @param proId
     * @return
     */
    public  static String getTime(Long proId){
        ProjectManagement projectManagement = pdfUtil.projectManagementService.getById(proId);
        LambdaQueryWrapper<LastCheck> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(LastCheck::getLastCheckId,projectManagement.getLastCheckId())
                .eq(LastCheck::getIsDelete, Constants.DELETE_STATUS_NORMAL);
        LastCheck lastCheck = pdfUtil.lastCheckMapper.selectOne(lambdaQueryWrapper);
        //考核开始时间为终验时间
        LocalDateTime localDateTime = lastCheck.getLastAdoptTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
        String startTime = String.valueOf(localDateTime).substring(0,String.valueOf(localDateTime).lastIndexOf("T")).replace("-","/");
        //考核时间暂定为大于终验时间半年
        LocalDateTime localDateTimeEndTime = localDateTime.plusMonths(6);
        String endTime = String.valueOf(localDateTimeEndTime).substring(0,String.valueOf(localDateTimeEndTime).lastIndexOf("T")).replace("-","/");
        return startTime+"-"+endTime;
    }
}
